package com.zzw.zim.system.service.impl;

import com.zzw.zim.common.exception.ServerException;
import com.zzw.zim.security.cache.TokenStoreCache;
import com.zzw.zim.security.user.UserDetail;
import com.zzw.zim.security.utils.TokenUtils;
import com.zzw.zim.system.dto.SysAccountLoginDTO;
import com.zzw.zim.system.service.SysAuthService;
import com.zzw.zim.system.service.SysLogLoginService;
import com.zzw.zim.system.vo.SysTokenVO;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 系统认证服务

 * @author XiaoJie
 * @date ${DATE} ${TIME}
 */
@Service
public class SysAuthServiceImpl implements SysAuthService {
	@Resource
	private  TokenStoreCache tokenStoreCache;
	@Resource
	private  AuthenticationManager authenticationManager;
	@Resource
	private HttpServletRequest request;
	@Resource
    private SysLogLoginService sysLogLoginService;

	@Override
	public SysTokenVO loginByAccount (SysAccountLoginDTO loginDto) {
		Authentication authentication;
		try {
			// 用户认证
			authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword()));
		} catch (BadCredentialsException e) {
			throw new ServerException("用户名或密码错误");
		} catch (DisabledException e) {
			throw new ServerException("该用户已被禁用！");
		}

		// 用户信息
		UserDetail user = (UserDetail) authentication.getPrincipal();

		// 生成 accessToken
		String accessToken = TokenUtils.generator();

		// 保存用户信息到缓存
		tokenStoreCache.saveUser(accessToken, user);

		//获取用户的过期时间
		Long expireTime = tokenStoreCache.getExpireTime(accessToken);

		user.setPassword("");
		return new SysTokenVO(accessToken, user.getId(),user,expireTime);
	}


	@Override
	public void logout (String accessToken) {
		// 用户信息
		UserDetail user = tokenStoreCache.getUser(accessToken);

		// 删除用户信息
		tokenStoreCache.deleteUser(accessToken);

		// 保存登录日志

	}

}
